package LeetCode.leetcode617;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution{
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(3);
        TreeNode node3 = new TreeNode(2);
        TreeNode node4 = new TreeNode(5);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;

        TreeNode nodea = new TreeNode(2);
        TreeNode nodeb = new TreeNode(1);
        TreeNode nodec = new TreeNode(3);
        TreeNode noded = new TreeNode(4);
        TreeNode nodee = new TreeNode(7);
        nodea.left = nodeb;
        nodea.right = nodec;
        nodeb.right = noded;
        nodec.right = nodee;

        preOrder(mergeTrees(node1,nodea));

    }
    public static TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        TreeNode node;
        if (root1 == null && root2 == null)
            return null;
        else if (root1 == null && root2 != null){
            //只有一个值
            node =  new TreeNode(root2.val);
            node.left = mergeTrees(null,root2.left);
            node.right = mergeTrees(null,root2.right);
        }else if (root1 != null && root2 == null){
            node =  new TreeNode(root1.val);
            node.left = mergeTrees(root1.left,null);
            node.right = mergeTrees(root1.right,null);
        }else {
            //都有值的情况下
            node = new TreeNode(root1.val+ root2.val);
            node.left = mergeTrees(root1.left,root2.left);
            node.right = mergeTrees(root1.right,root2.right);
        }
        return node;
    }

    public static void preOrder(TreeNode node){
        if (node != null){
            System.out.println(node.val);
            preOrder(node.left);
            preOrder(node.right);
        }
    }
}